package edu.njfu.wigetdemo.adapter

import android.app.Activity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.ImageView
import android.widget.TextView
import edu.njfu.wigetdemo.R
import edu.njfu.wigetdemo.model.Fruit
import kotlinx.android.synthetic.main.fruit_item_layout.view.*

class FruitAdapter(activity:Activity,val resouceId:Int,data:List<Fruit>): ArrayAdapter<Fruit>(activity,resouceId,data) {
    //定义一个数据类viewHolder
    inner class ViewHolder(val fruitImage: ImageView,val fruitName: TextView)
    override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
        val view:View
        val  viewHolder:ViewHolder
        if(convertView==null) {
            view = LayoutInflater.from(context).inflate(resouceId, parent, false)
            val fruitImage:ImageView=view.findViewById<ImageView>(R.id.fruitImage)
            val fruitName:TextView=view.findViewById(R.id.fruitName)
            viewHolder=ViewHolder(fruitImage,fruitName)
            //设置view的标签
            view.tag=viewHolder

        }else{
            view=convertView
            viewHolder=view.tag as ViewHolder
        }
        val fruit=getItem(position)//获取当前的Fruit的实例
        if(fruit!=null){
            viewHolder.fruitImage.setImageResource(fruit.imageId)
            viewHolder.fruitName.text=fruit.name
        }
        return view
    }
}